package com.hx.hospital.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.hx.common.constant.RedisKey;
import com.hx.common.exception.CustomerException;
import com.hx.common.exception.MessageCode;
import com.hx.hospital.mapper.UserMapper;
import com.hx.hospital.pojo.User;
import com.hx.hospital.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userRepository;

    /*@Autowired
    private RestTemplate restTemplate;*/

    public static final String LOGIN="sfvasfewsjkfbacvasjcasjcj";

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";


    //微信授权登录
    @Override
    public Map<String, String> wxLogin( String code) throws CustomerException {

        Map<String,String> result=new HashMap<>();

        //配置前端给的appId和secret 不要配置我的!!!
        String appId = "wxb94a13c3ea18a220";
        String secret = "3448b3977626386cee3eb1ccf926e24d";


        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        String jsonData = restTemplate.getForObject(url, String.class);

        log.info("微信登录的数据为:{}",jsonData);

        if (jsonData.contains( "errcode")) {
            log.info("微信授权失败!");
            result.put("msg", "微信授权失败");
            return result;
        }


        JSONObject jsonObject = JSONObject.parseObject(jsonData);

        String openId=jsonObject.getString("openid");
        String session_key=jsonObject.getString("sessionKey");

        log.info("openid:{}",openId);


        User user = userRepository.findUserByOpenId(openId);
        if(user==null){
            //匿名注册
            log.info("匿名绑定微信账户:{}",openId);
            user=new User();
            //用户名也可以让前端获取传过来，根据具体情况修改
            user.setUsername("用户:"+openId);
            user.setStatus(1);//正常账号
            user.setOpenId(openId);
            userRepository.insert(user);
        }

        if(!StringUtils.isEmpty(user.getToken())){
            //获取上次的token,获取后移除上一次的登录信息
            redisTemplate.delete(LOGIN+user.getToken());
        }

        //生成token，存储登录信息
        String token= UUID.randomUUID().toString().replace("-","");
        //更新ip和登录时间
        user.setToken(token);
        user.setLastLoginTime(new Date());
        userRepository.updateByPrimaryKey(user);

        user.setSessionKey(session_key);

        redisTemplate.boundValueOps(LOGIN+token).set(user);
        //时间自己根据具体情况配置
        redisTemplate.boundValueOps(LOGIN+token).expire(60*60*120, TimeUnit.SECONDS);


        result.put("token",token);
        return result;
    }

    //短信一键登录
    @Override
    public Map<String, String> login(String phone, String code) throws CustomerException {

        //一键登录

        //1.获取服务器存储的验证码
        String serverCode= (String) redisTemplate.boundValueOps(RedisKey.LOGIN_SMS +phone).get();

        if(StringUtils.isEmpty(serverCode)){
            //验证码失效
            throw  new CustomerException(MessageCode.LOGIN_SMS_EXPIRE);
        }
        if(!code.equals(serverCode)){
            //验证码输入错误
            throw  new CustomerException(MessageCode.LOGIN_SMS_ERROR);
        }

        User user = userRepository.findUserByPhone(phone);
        if(user==null){
            //匿名注册
            System.out.println("用户没有账号，匿名注册:"+phone);
            user=new User();
            user.setPhone(phone);
            user.setUsername("用户:"+phone);
            user.setStatus(1);//正常账号

            userRepository.insert(user);

        }

        if(user.getStatus()!=1){
            throw new CustomerException(MessageCode.USER_NO);
        }

        //我怎么知道他是手机端?

        //获取上次的token,获取后移除上一次的登录信息
        if(!StringUtils.isEmpty(user.getToken())){
            redisTemplate.delete(LOGIN+user.getToken());
        }

        //生成token，存储登录信息
        String token=UUID.randomUUID().toString().replace("-","");

        //处理登录

        // 设置ip  去掉了


        user.setLastLoginTime(new Date());
        user.setToken(token);
        userRepository.insert(user);//更新ip和登录时间


        redisTemplate.boundValueOps(LOGIN+token).set(user);
        redisTemplate.boundValueOps(LOGIN+token).expire(60*60*2, TimeUnit.SECONDS);

        Map<String,String> result=new HashMap<>();
        result.put("token",token);

        return result;
    }


    @Override
    public User queryUserByToken(String token) throws CustomerException {

        User user = (User) redisTemplate.boundValueOps(LOGIN + token).get();
        if (ObjectUtils.isEmpty(user)) {
            System.out.println("无效token");
            throw new CustomerException(MessageCode.TOKEN_NO);
        }

        //要更新失效时间
        redisTemplate.boundValueOps(LOGIN+token).expire(60*60*48, TimeUnit.SECONDS);

        return user;
    }

}
